# -*- coding: utf-8 -*-

import os
import csv
from log.logger import logger


def csv_load(cfile):
    '''
    csv ---> [{'a':'1A', 'b':'2B', 'c':'3C'}, {'a':'4D', 'b':'5E', 'c':'6F'}]
    csv.DictReader is also OK
    '''
    if os.path.exists(cfile):
        try:
            with open(cfile, 'r') as csv_file:
                reader = csv.reader(csv_file)

                # reader is an iterator
                title = next(reader)
                title = [item.strip() for item in title]

                obj = []
                for row in reader:
                    row = [item.strip() for item in row]
                    obj.append(dict(zip(title, row)))
                # logger.info("Load [{0}] to python object [{1}] successfully!".format(cfile, obj))
        except Exception, e:
            obj = None
            logger.error("Load [{0}] to python object failed: [{1}]".format(cfile, e))
    else:
        obj = None
        logger.error("Load [{0}] to python object failed! CSV file [{0}] do not exist!".format(cfile))

    return obj


def csv_dump(obj, cfile):
    '''
    [{'a':'1A', 'b':'2B', 'c':'3C'}, {'a':'4D', 'b':'5E', 'c':'6F'}] ---> csv
    csv.DictWriter is also OK
    '''
    try:
        with open(cfile, "w") as csv_file:
            writer = csv.writer(csv_file)

            title = obj[0].keys()
            writer.writerow(title)

            for record in obj:
                row = record.values()
                writer.writerow(row)
            # logger.info("Dump [{0}] to csv file [{1}] successfully!".format(obj, cfile))
    except Exception, e:
        logger.error("Dump [{0}] to csv file [{1}] failed: [{2}]".format(obj, cfile, e))

